package com.ruangong.GitClient.app.TravelExpense;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.ruangong.GitClient.R;
import com.ruangong.GitClient.app.TravelExpense.Expense;

import java.util.List;

public class ExpensesListAdapter extends ArrayAdapter<Expense> {

    private LayoutInflater inflater;

    // Constructor
    public ExpensesListAdapter(Context context, List<Expense> expenses) {
        super(context, 0, expenses);
        inflater = LayoutInflater.from(context);
    }

    // ViewHolder class
    private static class ViewHolder {
        TextView expenseNameTextView;
        TextView expenseAmountTextView;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        ViewHolder holder;

        // Check if an existing view is being reused, otherwise inflate the view
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.item_expense, parent, false);
            holder = new ViewHolder();
            holder.expenseNameTextView = convertView.findViewById(R.id.expenseNameTextView);
            holder.expenseAmountTextView = convertView.findViewById(R.id.expenseAmountTextView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        // Get the data item for this position
        Expense expense = getItem(position);

        // Populate the data into the template view using the data object
        if (expense != null) {
            holder.expenseNameTextView.setText(expense.getName());
            holder.expenseAmountTextView.setText(String.valueOf(expense.getAmount()));
        }

        // Return the completed view to render on screen
        return convertView;
    }
}



